import re
 
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.models import Group
from django.db.models.fields.files import FieldFile
from django.forms.models import model_to_dict
from rest_framework import serializers
from django.core.cache import cache
import phonenumbers
 
User = get_user_model()
 
class MobileLoginSerializer(serializers.Serializer):
    mobile = serializers.CharField(write_only=True)
    sms = serializers.CharField(write_only=True)
 
    def validate(self, attrs):
        mobile = attrs.get('mobile')
        sms = attrs.get('sms')
        # 从数据库中获取存储的验证码, 检查存储的验证码与输入的验证码是否匹配
        if cache.has_key(mobile):
            stored_sms = cache.get(mobile)
        else:
            serializers.ValidationError("未找到验证码")
        if mobile and sms:
            if str(stored_sms) != str(sms):
                raise serializers.ValidationError("验证码错误, sms:{}, stored_sms: {}".format(sms, stored_sms))
            user = User._default_manager.get(mobile=mobile)
 
            if not user:
                msg = f"Access denied: wrong mobile: {mobile} or sms: {sms}."
                raise serializers.ValidationError(msg)
        else:
            msg = 'Both "mobile" and "sms" are required.'
            raise serializers.ValidationError(msg)
        attrs['user'] = user
        return attrs
 
 
class SendSMSCodeSerializer(serializers.Serializer):
    mobile = serializers.CharField(write_only=True)
 
    def validate(self, attrs):
        mobile = attrs.get('mobile')
        mobile_string = phonenumbers.parse('+86{}'.format(mobile), None)
        if not phonenumbers.is_valid_number(mobile_string):
            raise serializers.ValidationError('号码不存在: {}'.format(mobile))
 
        if mobile:
            user = User._default_manager.get(mobile=mobile)
            if not user:
                msg = f"未找到该号码相关的注册用户"
                raise serializers.ValidationError(msg)
        else:
            msg = '手机号码错误, 请重新输入'
            raise serializers.ValidationError(msg)
 
        return attrs